<template>
    <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
        <BasicForm @register="registerForm" @eventFormModel="eventFormModel">
            <template #formFooter v-if="dataSource.length">
                <h2 style="font-size:16px; width:100%">成本计算器</h2>
                <a-table style="width:100%" bordered :dataSource="dataSource" :columns="columnss" :pagination="false">
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.key === 'totalCost'">
                        {{ record.totalCost ? parseFloat(record.totalCost).toFixed(0) : 0 }}
                      </template>
                      <template v-if="column.key === 'totalAmount'">
                        {{ record.totalAmount ? parseFloat(record.totalAmount).toFixed(0) : 0 }}
                      </template>
                      <template v-if="column.key === 'remainderBudget'">
                        {{ record.remainderBudget ? parseFloat(record.remainderBudget).toFixed(0) : 0 }}
                      </template>
                        <template v-if="column.key === 'costStatus'">
                            <a-tag v-if="record.costStatus == 1" color="green">正常</a-tag>
                            <a-tag v-if="record.costStatus == 2" color="orange">接近阈值</a-tag>
                            <a-tag v-if="record.costStatus == 3" color="red">预算使用率超出时间进度</a-tag>
                        </template>
                        <template v-if="column.key === 'costPercent'">
                            {{ (record.costPercent * 100) > 0 ? (record.costPercent * 100).toFixed(0) : 0 }}%
                        </template>
                    </template>
                </a-table>
            </template>
            <template #nameDom="{model, field}">
                <a-input
                v-model:value="model[field]"
                placeholder="付款名称"
                enter-button="名称"
                v-if="(payType == 1 && isLog == 2) || payType == 3"
                size="size"
                />
                <a-select
                v-model:value="pValue"
                style="width: 100%"
                placeholder="付款名称"
                :options="userList"
                v-else
                @change="a"
                :disabled="(payType == 1 || payType == 2) && projectId ? false : true"
                ></a-select>
            </template>
            <template #typeDom="{model, field}" v-if="payType == 1">
                <a-radio-group v-model:value="isLog" @change="c">
                    <a-radio :value="1">有记录</a-radio>
                    <a-radio :value="2">没记录</a-radio>
                </a-radio-group>
            </template>
            <template #InputDom="{model, field}">
                <a-input
                v-model:value="bfb"
                placeholder="100"
                suffix='%'
                size="size"
                disabled
                v-if="payType == 3"
                @change="bfbFun"
                />
                <a-input
                v-else
                v-model:value="bfb"
                placeholder="百分比"
                suffix='%'
                size="size"
                @change="bfbFun"
                />
            </template>
        </BasicForm>
        <VerifyInfo :verifyType="4" ref="childRef"/>
    </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import VerifyInfo from './verifyInfo.vue'
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../MonsterSupplierCostSubmit.data';
    import {saveOrUpdate, queryCurrentCostBudget, SipplierPaymentModule} from '../MonsterSupplierCostSubmit.api';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { countStatusSupplier, notEmpty } from '/@/utils/tool'
    import { USER_INFO_KEY } from '/@/enums/cacheEnum'
    import { getAuthCache } from '/@/utils/auth'
    let user:any = getAuthCache(USER_INFO_KEY) || {}
    const childRef = ref()

    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    let oId = ''
    const isType = ref('add')

    const dataSource = ref<any>([])
    const dataOldSource = ref<any>('')
    const projectId = ref('')
    const payType = ref('')
    const userList = ref([])
    const pValue = ref('')
    const bfb:any = ref(0)
    const isLog = ref('')
    // 年度第三方总额 2、已使用额度 3、已使用百分比 4、当前剩余 5、当前状态
    const columnss = ref([
        {
            title: '年度第三方总额',
            dataIndex: 'totalCost',
            key: 'totalCost',
        },
        {
            title: '已使用额度',
            dataIndex: 'totalAmount',
            key: 'totalAmount',
        },
        {
            title: '已使用百分比',
            dataIndex: 'costPercent',
            key: 'costPercent',
        },
        {
            title: '当前剩余',
            dataIndex: 'remainderBudget',
            key: 'remainderBudget',
        },
        {
            title: '当前状态',
            dataIndex: 'costStatus',
            key: 'costStatus',
        },
    ])

    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate, updateSchema}] = useForm({
        labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        dataSource.value = []
        dataOldSource.value = ''
        oId = ''
        isType.value = data.isType
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
            bfb.value = data.record && data.record.percent * 100
            pValue.value = data.record && data.record.name
            await list(data.record)
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
            childRef.value.childMethod(data.record)
        }else {
            bfb.value = ""
            childRef.value.childMethod()
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            const { createMessage } = useMessage()
            console.log('values', values)
            if(!notEmpty(values, ['projectId', 'payType','name', 'payObject', 'amount', 'fax', 'receiveBank', 'receiveAccount', 'receiveName'])) {
                return createMessage.warn('请完善信息')
            }
            if(!bfb.value){
                return createMessage.warn('请填写百分比')
            }
            // 如果同一个名字的percent + 本次百分比 超过1 不允许提交
            let f = values.uploadFile ? JSON.parse(values.uploadFile) : []
            let a = values.percent ? Number(bfb.value) + Number(values.percent?values.percent:0) : 100
            if(values.payType !=3) {
                console.log('不等于3')
                if(values.name && values.name.indexOf(' (已付款') >-1) {
                    const str = values.name
                    const startChar = '已付款'
                    const endChar = '%'

                    const startx = str.indexOf(startChar) + startChar.length
                    const endx = str.indexOf(endChar)
                    const substr = str.slice(startx, endx)

                    console.log(Number(bfb.value), Number(substr) ,'substr')
                    values.percent = Number(bfb.value)  / 100
                    if(Number(bfb.value) + Number(parseInt(substr)) > 100) {
                        return createMessage.warn('尾款超100%不能提交');
                    }
                }

                if(values.name && values.name.indexOf(' (已付款') <0 || !values.name) {
                    values.percent = Number(bfb.value) / 100
                }

                // if(!values.name) {
                //     values.percent = Number(bfb.value) / 100
                // }

                if(values.name && values.name.indexOf(' (') >-1) {
                    const substr = values.name.substring(0, values.name.indexOf(' ('))
                    console.log('name', substr)
                    values.name = substr
                }

            } else {
                values.percent = 1
                values.name = '全额付款'
            }
            console.log('----------------',values)
            // Number(values.amount) - Number(Math.abs(dataSource.value[0].remainderBudget))
            if( dataSource.value[0].remainderBudget <0) {
                return createMessage.warn('申请额度超出预算，无法提交')
            }
            let file:any = []
            f.forEach((url) => {
                file.push({
                    annexName: url.fileName,
                    annexType: url.fileType,
                    url: url.filePath,
                })
            })
            values.uploadFile = JSON.stringify(file)
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(Object.assign(values,{annex:JSON.stringify(file),status: 1}), isUpdate.value);
            userList.value = []
            bfb.value = ''
            pValue.value = ''
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }

    function c () {
        pValue.value = ''
        bfb.value = ''
    }

    function bfbFun(e) {
        if(bfb.value >100) bfb.value = 100
    }

    async function list (item) {
        let res = await queryCurrentCostBudget({operateType:2, submitType:1,projectId:item.projectId,id:item.id,payAmount: item.amount ? item.amount : 0})//.then(res => {
            dataSource.value = [res]
            dataOldSource.value = JSON.stringify(res)
            dataSource.value[0].payAmount = item.amount ? item.amount : 0
            console.log('costStatus',dataSource.value[0].costStatus)
        // })
    }
    function a (e) {
        userList.value.forEach((i:any,index) => {
            if(index == e) {
                bfb.value = i.totalPercent
                setFieldsValue({name: i.label})
            }
        })
    }

    async function listName() {
        let r = await SipplierPaymentModule({projectId:projectId.value,userId:user.id})
        let arr:any = []
        r.forEach((i,index) => {
            arr.push({
                totalPercent: parseInt(i.totalPercent * 100),
                value: index,
                label: i.name,
            })
        })
        if(arr.length) {
            isLog.value = 1
        }
        userList.value = arr
    }

    async function eventFormModel (e) {
        if(isType.value =='info') {
            setTimeout(() => {
                isType.value = 'add'
            },1000)
            return
        }
        if(e && e.projectId && oId != e.projectId) {
            oId = e.projectId
            projectId.value = e.projectId
            await list(e)
            listName()
        }

        console.log(payType.value,e.payType)
        if(e.name && (payType.value != e.payType)) {
            isLog.value = ''
            pValue.value = ''
            setFieldsValue({name: ''})
        }

        payType.value = e.payType ? e.payType : ''
        // 预付款 尾款
        if(e && e.payType == 3) {
            pValue.value = ''
            bfb.value = 100

            // updateSchema({field: 'name', label: ''})
        }else if(e.payType){
            updateSchema({field: 'name', label: '付款名称'})
        }else {
            setTimeout(() => {
                updateSchema({field: 'jl', label: ''})
                updateSchema({field: 'name', label: ''})
            })
        }

        if(e && e.payType == 1) {
            setTimeout(() => {
                updateSchema({field: 'jl', label: '是否有记录'})
                updateSchema({field: 'name', label: '付款名称'})
            })
        }else if(e.payType) {
            updateSchema({field: 'jl', label: ''})
        }

        if(e.amount, dataSource.value.length) {
            countStatusSupplier(1,dataSource.value, dataOldSource.value, e.amount)

            // let cost = (Number(dataSource.value[0].currentAvablieCost) - (Number(dataSource.value[0].currentMonthConsume) + Number(e.amount))) / dataSource.value[0].currentAvablieCost
            // if(cost < dataSource.value[0].remindThreshold && cost > dataSource.value[0].warningThreshold) {
            //   dataSource.value[0].costStatus = 2
            // }
            // else if(cost < dataSource.value[0].warningThreshold) {
            //     dataSource.value[0].costStatus = 3
            // }
            // else {
            //     dataSource.value[0].costStatus = 1
            // }

            // timePercent >= (totalAmount + e.Amount（输入金额）) /totalCost  1

            let n = e.amount ? Number(Number(dataSource.value[0].totalAmount) + Number(e.amount)) / Number(dataSource.value[0].totalCost) : 0
            console.log('成本当前使用百分比',n)
            if(Number(dataSource.value[0].timePercent) >= Number(n * 100)) {
                dataSource.value[0].costStatus = 1
            }
            if(Number(dataSource.value[0].timePercent) < Number(n * 100)) {
                dataSource.value[0].costStatus = 3
            }
          console.log('时间消耗百分比',Number(dataSource.value[0].timePercent) )
            dataSource.value[0].payAmount = e.amount
        }
        if(!e.amount && dataSource.value.length) {
            dataSource.value[0].payAmount = ''
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
